import ipfsApi from 'ipfs-api';
import WEB3 from 'web3';
import WalletList from '../src/compiled/WalletList.json';
import Wallet from '../src/compiled/Wallet.json';
import Order from '../src/compiled/Order.json';
import address from './address';
import IceNotification from '@icedesign/notification';
import { Message } from '@alifd/next';

let ipfs = ipfsApi("ipfs.infura.io", "5001", {"protocol": "https"});
let ipfsPrefix = "https://ipfs.infura.io:5001/api/v0/cat?arg=";

let web3;
if(window.web3) {
  web3 = new WEB3(window.web3.currentProvider);
}else {
  IceNotification.warning({
      message: '没有检测到以太坊插件',
      description: '请安装metaMask或者激活'
  });
}

let walletListContract = new web3.eth.Contract(WalletList.abi, address);
let getWalletContract = (addr) => new web3.eth.Contract(Wallet.abi, addr);
let getOrderContract = (addr) => new web3.eth.Contract(Order.abi, addr);

function saveImageToIpfs(file) {
  Message.show({
    type: 'loading',
    content: '上传图片中，网速较慢，请等待片刻'
  });
  return new Promise(function(resolve, reject) {
    let reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onloadend = async () => {
      const buffer = Buffer.from(reader.result);
      await ipfs.add(buffer).then((response) => {
        console.log('response', response);
        resolve(response[0].hash);
        Message.hide();
      }).catch((error) => {
        console.log(error);
        reject(error);
      });
    };
  });
}

export {
  web3,
  ipfs,
  ipfsPrefix,
  walletListContract,
  getWalletContract,
  getOrderContract,
  saveImageToIpfs
}